package com.catmiw.swt;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.catmiw.wyz.util.NetUtils;

public class EnglishPronunciationDownloader implements Runnable {
	private String url;
	private String savefilename;
	private NetFileGetter getter;

	public EnglishPronunciationDownloader(String url,
			String savefilename,NetFileGetter getter) {
		this.url = url;
		this.savefilename = savefilename;
		this.getter=getter;
	}

	public void run() {
		byte[] b = NetUtils.getFileBytesStreamFromNet(url);
		if(b!=null&&b.length>2){
			if ((b[0]&0xff)!=0xff||(b[1]&0xe0)!=0xe0){
				getter.afterLoad(false);
			}
		} else {
			getter.afterLoad(false);
		}
		
		BufferedOutputStream out = null;
		try {
			out = new BufferedOutputStream(new FileOutputStream(savefilename));
			System.out.println(savefilename);
			out.write(b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		getter.afterLoad(true);
	}

	public static void main(String[] args) {
		new Thread(
				new EnglishPronunciationDownloader("http://res-tts.iciba.com/6/d/4/6d4b62960a6aa2b1fff43a9c1d95f7b2.mp3",
						"d:/123.mp3",new NetFileGetter(){

							public void afterLoad(boolean success) {
								System.out.println(success);
								
							}
					
				})).run();
	}
}
